package io.yunho.spring.security.learn.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.yunho.spring.security.learn.demo.entity.Users;
import io.yunho.spring.security.learn.demo.mapper.UserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: Jason
 * @date: 2021/4/22 10:17
 * @description:
 */
@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//        List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("ADMIN");
//        return new User("mary",new BCryptPasswordEncoder().encode("123"),list);
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username",s);
        Users user = userMapper.selectOne(wrapper);
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("ADMIN,ROLE_SALE");
        return new User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),list);
    }
}
